package com.yql.common.service;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.yql.biz.domain.User;
import com.yql.biz.mapper.UserMapper;
import com.yql.common.config.JWTConfig;
import com.yql.common.utils.JwtUtils;
import com.yql.commonextend.response.CommonResponse;
import com.yql.commonextend.response.ResponseConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class PassLoginService {

    @Autowired
    UserMapper userMapper;

    public CommonResponse verifyLogin(String token){
        if (token == null) {
            CommonResponse commonResponse = CommonResponse.RespWithCodeMsg(ResponseConstant.RESP_NOT_LOGIN_ERROR_CODE, ResponseConstant.RESP_NOT_LOGIN_ERROR_MESG);
            return commonResponse;
        }
        //获取token中的user
        User user = null;
        try {
            log.info("进入verifyLogin 逻辑");
            user =  JwtUtils.getUser(token, User.class);
            log.info("解析User为==》{}",user);
        }catch (Exception e){
            log.error("PassLoginService异常001", e);
            CommonResponse commonResponse = CommonResponse.RespWithCodeMsg(ResponseConstant.RESP_NOT_LOGIN_ERROR_CODE, ResponseConstant.RESP_NOT_LOGIN_ERROR_MESG);
            return commonResponse;
        }
        if (user == null) {
            CommonResponse commonResponse = CommonResponse.RespWithCodeMsg(ResponseConstant.RESP_NOT_LOGIN_ERROR_CODE, ResponseConstant.RESP_NOT_LOGIN_ERROR_MESG);
            return commonResponse;
        }
        // 验证 token
        try {
            JwtUtils.verify(JWTConfig.getSecret(), token);
        }catch (TokenExpiredException e){
            log.error("PassLoginService异常002", e);
            CommonResponse commonResponse = CommonResponse.RespWithCodeMsg(ResponseConstant.RESP_NOT_LOGIN_ERROR_CODE, ResponseConstant.RESP_NOT_LOGIN_ERROR_MESG);
            return commonResponse;
        }catch (Exception e){
            log.error("PassLoginService异常003", e);
            CommonResponse commonResponse = CommonResponse.RespWithCodeMsg(ResponseConstant.RESP_RUNTIME_ERROR_CODE, ResponseConstant.RESP_RUNTIME_ERROR_MESG);
            return commonResponse;
        }
        return CommonResponse.success();
    }
}
